//
//  RegisterViewController.m
//  PigMarket
//
//  Created by Felix on 2019/3/12.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "RegisterViewController.h"

#import "AccountView.h"

#import "LoginViewController.h"
#import "SelectInviterViewController.h"
#import "GetMessageCodeParam.h"
#import "RegisterAgreementAlertView.h"

@interface RegisterViewController ()

/**
 logoImageView
 */
@property (nonatomic , strong) UIImageView *logoImageView;

/**
 accountView
 */
@property (nonatomic , strong) AccountView *accountView;

/**
 registerBtn
 */
@property (nonatomic , strong) UIButton *registerBtn;

/**
 loginTip
 */
@property (nonatomic , strong) YYLabel *loginTip;
/**
 注册协议弹框自定义view
 */
@property (nonatomic , strong) RegisterAgreementAlertView *registerAgreementAlertView;
/**
 是否同意注册协议
 */
@property (nonatomic , assign) BOOL isAgreeAgreement;
@end

@implementation RegisterViewController

#pragma mark - view life cycle

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.view.backgroundColor = KWhiteColor;
    [self setUpView];
}


#pragma mark - init method
- (void)setUpView {
    [self initView];
    [self initLayout];
    [self initAction];
}

- (void)initView {
    [self.view addSubview:self.logoImageView];
    [self.view addSubview:self.accountView];
    [self.view addSubview:self.registerBtn];
    [self.view addSubview:self.loginTip];
    [self showRegisterAgreement];

}

- (void) initLayout {
    [self.logoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(TJ_NavBarHeight+10);
    }];
    [self.accountView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.logoImageView.mas_bottom).offset(30);
        make.left.right.mas_equalTo(0);
    }];
    [self.registerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.accountView.mas_bottom).offset(30);
        make.height.mas_equalTo(48);
        make.centerX.mas_equalTo(0);
        make.left.mas_equalTo(30);
        make.right.mas_equalTo(-30);
    }];
    [self.loginTip mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.registerBtn.mas_right);
        make.top.mas_equalTo(self.registerBtn.mas_bottom).offset(20);
    }];
}

- (void) initAction {
    RACSignal *sendVerifyStateSignal = [self.accountView.accountField.rac_textSignal map:^id _Nullable(NSString * _Nullable phoneNum) {
        return @([phoneNum isValidPhoneNumber]);
    }];
    
    RACSignal *countDowningSignal = RACObserve(self.accountView.verifyBtn, isCountDowning);
    RAC(self.accountView.verifyBtn,enabled) = [RACSignal combineLatest:@[sendVerifyStateSignal,countDowningSignal] reduce:^id _Nonnull(NSNumber *sendVerifyState, NSNumber *countDowningState){
        return @(sendVerifyState.boolValue && !countDowningState.boolValue);
    }];
    [self.accountView.verifyBtn addTarget:self action:@selector(getVerifyCodeTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.registerBtn addTarget:self action:@selector(registerBtnTapped) forControlEvents:UIControlEventTouchUpInside];
    
    //注册协议
    [self.registerAgreementAlertView setPrivacyAgreementBlock:^{
        
        NSLog(@"__________________________注册协议");
    }];
    //隐私协议
    [self.registerAgreementAlertView setRegisterAgreementBlock:^{
        NSLog(@"__________________________隐私协议");

    }];
}


#pragma mark - delegate

#pragma mark - target action

- (void)getVerifyCodeTapped {

    [self getVerifyCodeRequest];
}

- (void)registerBtnTapped {

    [self registerRequest];
}


#pragma mark - private method
//获取验证码
- (void)getVerifyCodeRequest {
    NSString *phone = self.accountView.accountField.text;
    if (![phone isValidPhoneNumber]) {
        [self toastWithContent:@"请输入手机号码"];
        return;
    }
    GetMessageCodeParam *param = [[GetMessageCodeParam alloc] init];
    param.phone = phone;
    param.type = GetMessageCodeTypeRegisterAndBind;
    
    @weakify(self);
    [[[PigMarketApi sharedInstance] getMessageCodeWithParam:param] subscribeNext:^(GetMessageCode * _Nullable x) {
        @strongify(self);
        [self.accountView.verifyBtn startCountDown];
        [self toastWithContent:@"验证码已发送手机，请注意查收"];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}


//注册 --》 登录
- (void)registerRequest {
    NSString *phone = self.accountView.accountField.text;
    NSString *verifyCode = self.accountView.verifyField.text;
    
    if (!self.isAgreeAgreement) {
        [self toastWithContent:@"请阅读并同意注册协议及隐私政策"];
        [self showRegisterAgreement];
        return;
    }
    if (![phone isValidPhoneNumber]) {
        [self toastWithContent:@"请输入手机号码"];
        return;
    }
    if ([verifyCode isBlankString]) {
        
        [self toastWithContent:@"请输入验证码"];
        return;
    }
    @weakify(self);
    [[[PigMarketApi sharedInstance] userRegisterWithAccount:phone verifyCode:verifyCode] subscribeNext:^(UserInfo * _Nullable x) {
        @strongify(self);
        
        //注册成功后 调用登录接口  存储用户信息
        [self getUserInfoRequestWithPhone:phone verifyCode:verifyCode];
     } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}
//注册成功后 调用登录接口  存储用户信息
- (void)getUserInfoRequestWithPhone:(NSString *)phone verifyCode:(NSString *)verifyCode {
    @weakify(self);
    [[[PigMarketApi sharedInstance] userLoginWithAccount:phone msgCode:verifyCode loginType:@(LoginTypeCode)] subscribeNext:^(UserInfo * _Nullable userInfo) {
        @strongify(self);
        
        //存数据
        [UserInfoDataProvider sharedInstance].userInfo = userInfo;
        [TokenCacheManager sharedInstance].memberToken = userInfo.memberToken;
        
        SelectInviterViewController *selectInviterViewController = [[SelectInviterViewController alloc] init];
        [self.navigationController pushViewController:selectInviterViewController animated:YES];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}


//注册协议弹框
- (void)showRegisterAgreement {
    @weakify(self);
    [self alertViewWithTitle:@"注册协议及隐私政策" contentView:self.registerAgreementAlertView btnTitle:@"同意" btnBlock:^{
        @strongify(self);
        self.isAgreeAgreement = YES;
    }];
}


- (void)pushToLoginVC {
    
    [self.navigationController.childViewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if ([obj isKindOfClass:[LoginViewController class]]) {
            [self.navigationController popToViewController:obj animated:YES];
        }
    }];
}


#pragma mark - getter and setter

- (UIImageView *)logoImageView {
    if (!_logoImageView) {
        _logoImageView = [[UIImageView alloc] init];
        _logoImageView.image = [UIImage imageNamed:@"login_logo"];
    }
    return _logoImageView;
}


- (AccountView *)accountView {
    if (!_accountView) {
        _accountView = [[AccountView alloc] init];
    }
    return _accountView;
}


- (UIButton *)registerBtn {
    if (!_registerBtn) {
        _registerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_registerBtn setBackgroundImage:[UIImage imageNamed:@"login_loginbtn_default"] forState:UIControlStateNormal];
        [_registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    }
    return _registerBtn;
}


- (YYLabel *)loginTip {
    if (!_loginTip) {
        _loginTip = [[YYLabel alloc] init];
        NSMutableAttributedString* text = [[NSMutableAttributedString alloc] initWithString:@"已有账号，直接登录"];
        text.yy_font = [UIFont middleFont];
        text.yy_color = [UIColor textGrayColor];
        NSRange range = NSMakeRange(text.length - 2, 2);
        @weakify(self)
        [text yy_setTextHighlightRange:range color:[UIColor primaryColor] backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
            @strongify(self)
            [self pushToLoginVC];
        }];
        _loginTip.attributedText = text;
    }
    return _loginTip;
}
- (RegisterAgreementAlertView *)registerAgreementAlertView {
    if(!_registerAgreementAlertView) {
        _registerAgreementAlertView = [[RegisterAgreementAlertView alloc] init];
    }
    return _registerAgreementAlertView;
}
@end
